package org.s170.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.Part;

public class FileUploadUtil {
	// 属性
	// 1.设置文件上传大小
	private long maxSize;
	// 2.设置允许上传文件的类型
	private List<String> alowFileExt = new ArrayList<String>();

	// 设置默认容量和默认允许上传的文件
	public FileUploadUtil() {
		//1MB
		this.maxSize = 1 * 1024 * 1024;
		this.setAlowFileExt("doc,jpg");
	}
	
	

	public long getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

	public List<String> getAlowFileExt() {
		return alowFileExt;
	}
	//ext = "doc,jpg" 
	public void setAlowFileExt(String ext) {
		if(ext!=null && !"".equals(ext)) {
			this.alowFileExt.clear(); 
		}
		String[] str = ext.split(",");
		for (String s : str) {
			this.alowFileExt.add(s);
		}
	}

	// 行为
	// 1.获取上传文件名
	// 获取上传文件名
	public String getFilename(String header) {
		String filename = "";
		int beginIndex = header.indexOf("filename=\"") + 10;
		int endIndex = header.lastIndexOf("\"");
		filename = header.substring(beginIndex, endIndex);
		return filename;
	}

	// 2.获取上传文件扩展名
	public String getFileExt(String filename) {
		String value = "";

		if (filename == null || filename.lastIndexOf('.') != -1
				&& filename.lastIndexOf('.') == filename.length() - 1)
			return "";

		int beginIndex = filename.lastIndexOf('.') + 1;
		int endIndex = filename.length();
		value = filename.substring(beginIndex, endIndex);

		return value;
	}

	// 3.上传
	public String upload(Part part, String path) {
		String newFilename = "" ;

		// 判断上传文件容量大小
		if (part.getSize() > this.getMaxSize()) {
			//r = 1 ;
			throw new RuntimeException("上传文件容量溢出，只能上传"+this.getMaxSize()/1024*1024+"MB文件") ;
			//return "上传失败，只能上传"+this.getMaxSize()/(1024*1024)+"MB的文件" ;
		}

		String header = part.getHeader("Content-Disposition");
		String filename = this.getFilename(header);
		String ext = this.getFileExt(filename);

		if (!this.getAlowFileExt().contains(ext)) {
			//r = 2 ;
			throw new RuntimeException("上传失败，只能上传文件的类型有："+this.getAlowFileExt().toString()) ;
			//return "上传失败，只能上传文件的类型有："+this.getAlowFileExt().toString() ;
		}

		newFilename = UUID.randomUUID().toString() + "." + ext ;
		String uploadFile = path + File.separator + newFilename;

		try {
			part.write(uploadFile);
		} catch (IOException e) {
			e.printStackTrace();
			return "上传失败" ;
			
		}
		return newFilename ;
	}

}
